package org.example.study.liaoxuefeng;

import org.testng.annotations.Test;

/**
 * @author: 默苍璃
 * @date: 2023-05-22 17:29
 * <p>
 * 中断线程
 */
public class ThreadInterrupt {

    class MyThread extends Thread {
        public void run() {
            int n = 0;
            while (!isInterrupted()) {
                n++;
                System.out.println(n + " hello!");
            }
        }
    }

    /**
     * 中断一个线程
     */
    @Test
    public void test1() throws InterruptedException {
        Thread t = new MyThread();
        t.start();
        // 暂停1毫秒 暂停的是主线程
        Thread.sleep(1);
        // 中断t线程
        t.interrupt();
        // 等待t线程结束
        t.join();
        System.out.println("end");
    }


    class MyThread1 extends Thread {
        public void run() {
            Thread hello = new HelloThread();
            // 启动hello线程
            hello.start();
            try {
                System.out.println("我马上进入等待状态");
                // 等待hello线程结束  MyThread1处于进入等待状态 会抛异常  结束等待状态
                hello.join();
                System.out.println("MyThread1 等待状态 结束");
            } catch (InterruptedException e) {
                System.out.println("1s过去了");
                System.out.println("interrupted!");
            }
            hello.interrupt();
        }
    }

    class HelloThread extends Thread {
        public void run() {
            int n = 0;
            while (!isInterrupted()) {
                n++;
                System.out.println(n + " hello!");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    break;
                }
            }

        }
    }

    /**
     * 如果线程处于等待状态，例如，t.join()会让main线程进入等待状态，此时，如果对main线程调用interrupt()，join()方法会立刻抛出InterruptedException
     */
    @Test
    public void test2() throws InterruptedException {
        Thread t = new MyThread1();
        t.start();
        Thread.sleep(1000);
        // 中断t线程
        t.interrupt();
        // 等待t线程结束
        t.join();
        System.out.println("end");
    }


    class HelloThread06 extends Thread {
        public volatile boolean running = true;

        public void run() {
            int n = 0;
            while (running) {
                n++;
                System.out.println(n + " hello!");
            }
            System.out.println("end!");
        }
    }

    /**
     * 另一个常用的中断线程的方法是设置标志位
     */
    @Test
    public void test3() throws InterruptedException {
        HelloThread06 t = new HelloThread06();
        t.start();
        Thread.sleep(1);
        // 标志位置为false
        t.running = false;
    }


}
